<route lang="json5" type="page">
{
  layout: 'login',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '登录',
  },
}
</route>

<template>
  <view class="flex justify-center items-center" style="height: 100vh">
    <view class="card-shadow">
      <wd-form ref="form" :model="model">
        <wd-cell-group border>
          <wd-input
            label="用户名"
            label-width="100px"
            prop="phone"
            clearable
            v-model="model.phone"
            placeholder="请输入手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
          />
          <wd-input
            label="密码"
            label-width="100px"
            prop="password"
            show-password
            clearable
            v-model="model.password"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </wd-cell-group>
        <view class="footer">
          <view>
            <wd-button type="primary" size="large" @click="handleSubmit" block>登录</wd-button>
          </view>
          <view class="mt-4">
            <wd-button type="success" size="large" @click="handleWxSubmit" block>
              微信登录
            </wd-button>
          </view>
        </view>
      </wd-form>
    </view>
    <wd-toast />
    <wd-popup
      v-model="getInfoShow"
      position="bottom"
      custom-style="height: 200px;"
      @close="handleInfoClose"
    >
      <view class="flex justify-center items-center">
        <view class="text-center">
          <view>是否授权获取您的头像和昵称信息？</view>
          <view>
            <wd-button @click="handleInfoClose">取消</wd-button>
            <wd-button open-type="getUserInfo | " lang="zh_CN" @getuserinfo="handleGetUserInfo">
              确认
            </wd-button>
          </view>
        </view>
      </view>
    </wd-popup>
    <wd-popup
      v-model="getPhoneShow"
      position="bottom"
      custom-style="height: 200px;"
      @close="handlePhoneClose"
    >
      <view class="flex justify-center items-center">
        <view class="text-center">
          <view>是否授权获取您的手机号？</view>
          <view>
            <wd-button @click="handlePhoneClose">取消</wd-button>
            <wd-button
              open-type="getPhoneNumber"
              lang="zh_CN"
              @getphonenumber="handleGetPhoneNumber"
            >
              确认
            </wd-button>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import { useToast } from 'wot-design-uni'
import { useUserStore } from '@/store'
import { http } from '@/utils/http'

const { success: showSuccess } = useToast()
const userStore = useUserStore()
const getInfoShow = ref(false)
const getPhoneShow = ref(false)
const toast = useToast()

const model = reactive<{
  phone: string
  password: string
}>({
  phone: '',
  password: '',
})

const form = ref()

function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        http({
          url: 'wx/base/password-login',
          method: 'POST',
          data: { username: model.phone, password: model.password },
        })
          .then((res) => {
            console.log(res)

            // 登录成功后，将 token 写入用户信息
            const userInfo = {
              nickname: res.msg.split(' ')[0],
              avatar: 'https://unpkg.com/wot-design-uni-assets/meng.jpg',
              // 密码登录获取的openid实际为userId
              openid: res.msg.split(' ')[2],
              token: res.msg.split(' ')[1],
              roleId: 3,
            }
            userStore.setUserInfo(userInfo)

            showSuccess({
              msg: '校验通过',
            })

            uni.reLaunch({
              url: '/pages/index/index',
            })
          })
          .catch((error) => {
            console.log(error, 'error')
          })
      }
    })
    .catch((error: any) => {
      toast.error(error)
    })
}

const handleWxSubmit = () => {
  uni.login({
    provider: 'weixin',
    success: (res) => {
      console.log(res.code)
      http({ url: 'wx/base/login', method: 'POST', data: { code: res.code } }).then((res) => {
        uni.getUserInfo({
          success: (infoRes) => {
            console.log(infoRes)
            const userInfo = {
              nickname: infoRes.userInfo.nickName,
              avatar: infoRes.userInfo.avatarUrl,

              // 从后端获取 openid 和 token
              openid: res.msg.split(' ')[0],
              token: res.msg.split(' ')[1],
              roleId: 4,
            }
            userStore.setUserInfo(userInfo)

            // 异步传送nickname和avatar到服务器
            sendUserInfoToServer(userInfo)

            showSuccess({
              msg: '微信登录成功',
            })

            uni.reLaunch({
              url: '/pages/index/index',
            })
          },
        })
      })
    },
  })
}

const sendUserInfoToServer = async (userInfo: {
  nickname: string
  avatar: string
  openid: string
  token: string
  roleId: number
}) => {
  try {
    await http({
      url: 'wx/base/userInfo',
      method: 'POST',
      data: {
        nickname: userInfo.nickname,
        avatar: userInfo.avatar,
        openid: userInfo.openid,
      },
    })
  } catch (error) {
    toast.error('上传用户信息失败' + error)
  }
}

const handleGetUserInfo = (e: any) => {}

const handleGetPhoneNumber = (e: any) => {}

const handleInfoClose = () => {
  getInfoShow.value = false
}
const handlePhoneClose = () => {
  getPhoneShow.value = false
}
</script>

<style lang="scss" scoped>
.footer {
  padding: 12px;
}

.card-shadow {
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgb(0 0 0 / 10%);
  transition: box-shadow 0.3s ease-in-out;
}

.card-shadow:hover {
  box-shadow: 0 6px 12px rgb(0 0 0 / 15%);
}
</style>
